package com.dxy.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxy.common.exp.ServiceException;
import com.dxy.common.pojo.Order;
import com.dxy.common.pojo.Product;
import com.dxy.common.pojo.User;
import com.dxy.common.user.UserContextHolder;
import com.dxy.common.vo.Result;
import com.dxy.order.mapper.OrderMapper;
import com.dxy.order.provider.ProductServiceProvider;
import com.dxy.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private ProductServiceProvider productServiceProvider;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public Order createOrder(String pid, int num) {
        Result<Product> productResult = productServiceProvider.findProductById(pid);
        Product product = productResult.getData();
        if (product == null) {
            throw new ServiceException("商品不存在");
        }
        Result reduceStockResult = productServiceProvider.reduceStock(pid, num);
        if (reduceStockResult.isFail()) {
            throw new ServiceException(reduceStockResult.getCode(), reduceStockResult.getMsg());
        }
        User user = UserContextHolder.getAuthUserSubject().user();
        Order order = new Order();
        order.setOrderName(product.getProductName() + "订单");
        order.setProductId(product.getPid());
        order.setProductName(product.getProductName());
        order.setTotal(num);
        order.setAmount(product.getProductPrice().multiply(new BigDecimal(num + "")));
        order.setUserId(user.getUid() + "");
        order.setUserName(user.getUsername());
        order.setCreateTime(new Date());
        orderMapper.insert(order);// TODO 此处先修改库存，再保存订单，后续考虑加上分布式事务
        return order;
    }
}
